package leeon.bbsbrower.actions;

import ipworks.IPWorksException;

import java.util.ArrayList;

import leeon.bbsbrower.models.BlockObject;
import leeon.bbsbrower.util.HTMLUtil;
import leeon.bbsbrower.util.HTTPBean;

public class BBSBlockAction {

	//获取所有讨论块的连接
	public static final String URL_BLOCK = Config.SERVER_URL + Config.SERVER_CGI + "bbsleft";
		
	//静态单例的block列表
	private static BlockObject[] blocks = null;
	
	/**
	 * 获取所有讨论块的方法
	 * @return
	 * @throws IPWorksException 
	 */
	public static BlockObject[] getBlocks() throws IPWorksException {
		if (blocks == null) {			
			HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			String content = http.get(URL_BLOCK);
			blocks = parseBlocks(content);
		}			
		return blocks;
	}
	
	/**
	 * 从html content解析出讨论块的方法
	 * @param content
	 * @return
	 */
	private static BlockObject[] parseBlocks(String content) {
		String block = HTMLUtil.findStr(content, 
				"<div id=\"EGroup\">", 
				"</a>\n</div>");
		String[] blocks = block.split("</a>");
		
		
		ArrayList<BlockObject> list = new ArrayList<BlockObject>();
		for (int i = 0; blocks != null && i < blocks.length; i ++) {
			if (blocks[i] != null && blocks[i].length() != 0) {
				String url = Config.SERVER_URL + HTMLUtil.findStr(blocks[i], "<a href=\"", "\"");
				String name = HTMLUtil.findStr(blocks[i], "<img src=\"/images/types/folder1.gif\">");
				BlockObject bo = new BlockObject(name.trim(), url);
				list.add(bo);
			}
		}
		if (list.size() != 0)
			return list.toArray(new BlockObject[0]);
		else
			return null;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {		
	}

}
